import pandas as pd

class DataHandler:
    def __init__(self, data_file, explanation_file=None):
        self.data_file = data_file
        self.explanation_file = explanation_file
        self.df = None
        self.explanations = None
    
    def load_data(self):
        """加载数据文件，并可选地加载术语解释文件。"""
        self.df = self._load_file(self.data_file)
        
        if self.explanation_file:
            self.load_explanations()

    def _load_file(self, file_path):
        """根据文件扩展名加载CSV或Excel文件。"""
        if file_path.endswith('.csv'):
            return pd.read_csv(file_path)
        elif file_path.endswith('.xlsx'):
            return pd.read_excel(file_path)
        else:
            raise ValueError(f"Unsupported file format: {file_path}. Please use .csv or .xlsx.")
    
    def load_explanations(self):
        """加载术语解释文件。"""
        self.explanations = self._load_file(self.explanation_file)

    def get_explanation(self, term):
        """根据术语返回其解释，若无解释则返回默认提示。"""
        if self.explanations is not None:
            matched_explanations = self.explanations[self.explanations['Term'].str.lower() == term.lower()]
            if not matched_explanations.empty:
                return matched_explanations.iloc[0]['Explanation']
        return f"No explanation found for term: {term}"

    def get_all_terms(self):
        """返回术语解释文件中的所有术语和解释。"""
        if self.explanations is not None:
            return dict(zip(self.explanations['Term'], self.explanations['Explanation']))
        else:
            return {}

    def display_explanations(self):
        """显示所有术语的解释，如果有可用的解释文件。"""
        if self.explanations is not None:
            print("Term Explanations:")
            print(self.explanations.to_string(index=False))
        else:
            print("No explanations available.")


